package com.cskaoyan.service;

import cn.hutool.core.date.DateTime;
import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.goods.MarketGoods;
import com.cskaoyan.bean.goods.MarketGoodsExample;
import com.cskaoyan.bean.goods.catbrand.MarketCategory;
import com.cskaoyan.bean.market.Category;
import com.cskaoyan.bean.market.Keyword;
import com.cskaoyan.bean.market.KeywordExample;
import com.cskaoyan.bean.user.SearchHistory;
import com.cskaoyan.bean.user.SearchHistoryExample;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.wxsearch.GoodsListBean;
import com.cskaoyan.bean.wxsearch.SearchIndexVO;
import com.cskaoyan.bean.wxsearch.SearchResult;
import com.cskaoyan.mapper.KeywordMapper;
import com.cskaoyan.mapper.SearchHistoryMapper;
import com.cskaoyan.mapper.goodsMapper.MarketGoodsMapper;
import com.cskaoyan.mapper.goodsMapper.catbrand.MarketCategoryMapper;
import com.cskaoyan.util.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @Description: ${DESCRIPTION}
 * @Author: 徐能雄
 * @Date: 2021/9/18 15:36
 */
@Service
public class WXSearchServiceImpl implements WXSearchService {

    @Autowired
    KeywordMapper keywordMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    @Override
    public SearchIndexVO searchIndex() {
        SearchIndexVO searchIndexVO = new SearchIndexVO();

        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria().andIsDefaultEqualTo(true).andDeletedEqualTo(false);
        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);
        searchIndexVO.setDefaultKeyword(keywords.get(0));

        KeywordExample keywordExample1 = new KeywordExample();
        KeywordExample.Criteria criteria1 = keywordExample1.createCriteria().andIsHotEqualTo(true).andDeletedEqualTo(false);
        List<Keyword> hotkeywords = keywordMapper.selectByExample(keywordExample1);
        searchIndexVO.setHotKeywordList(hotkeywords);

        Integer userId = 1;
        //TODO
//        Subject subject = SecurityUtils.getSubject();
//        User user = (User) subject.getPrincipal();
//        userId = user.getId();

        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        searchHistoryExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        ArrayList<SearchIndexVO.HistoryKeywordListBean> historyKeywordListBeans = new ArrayList<>();
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        for (SearchHistory searchHistory : searchHistories) {
            SearchIndexVO.HistoryKeywordListBean historyKeywordListBean = new SearchIndexVO.HistoryKeywordListBean();
            historyKeywordListBean.setKeyword(searchHistory.getKeyword());
            historyKeywordListBeans.add(historyKeywordListBean);
        }
        searchIndexVO.setHistoryKeywordList(historyKeywordListBeans);

        return searchIndexVO;
    }

    @Override
    public BaseRespVo searchHelper(String keyword) {

        KeywordExample keywordExample = new KeywordExample();
        keywordExample.createCriteria().andDeletedEqualTo(false).andKeywordLike("%"+keyword+"%");
        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);

        List<String> collect = keywords.stream().map(Keyword::getKeyword).collect(Collectors.toList());
        return BaseRespVo.ok(collect);

    }

    @Override
    public BaseRespVo result(BaseParam baseParam, Integer categoryId, Integer brandId, String keyword, Boolean isHot, Boolean isNew) {
        Integer id=1;

//        Subject subject = SecurityUtils.getSubject();
//        User user = (User) subject.getPrincipal();
//        id = user.getId();

        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria().andDeletedEqualTo(false);
        criteria.andKeywordEqualTo(keyword);
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
        if (searchHistories.isEmpty()) {
            SearchHistory wx = SearchHistory.builder().userId(id).updateTime(DateTime.now()).addTime(DateTime.now()).deleted(false).from("wx").keyword(keyword).build();
            int insert = searchHistoryMapper.insert(wx);
        }

        PageUtil.start(baseParam);

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.setOrderByClause(baseParam.getSort()+" "+baseParam.getOrder());

        MarketGoodsExample.Criteria criteria1 = goodsExample.createCriteria();
        if (keyword!=null&&!"".equals(keyword)){
            criteria1 = criteria1.andKeywordsLike("%"+keyword+"%");
            goodsExample.or().andNameLike("%"+keyword+"%");
        }else if (isHot!=null&&isHot==true){
            criteria1.andIsHotEqualTo(true);
        }else if (isNew!=null&&isNew==true){
            criteria1.andIsNewEqualTo(true);
        }else {
            return BaseRespVo.fail("错误参数失败");
        }

        List<MarketGoods> goods = marketGoodsMapper.selectByExample(goodsExample);

        SearchResult selectResult = new SearchResult();
        List<GoodsListBean> goodsListBeans = new ArrayList<>();
        TreeSet categories = new TreeSet((Comparator<Category>) (o1, o2) -> o1.getId()-o2.getId());
        for (MarketGoods good : goods) {
            if (categoryId!=0 && categoryId.compareTo(good.getCategoryId())==0){
                GoodsListBean build = GoodsListBean.builder().brief(good.getBrief()).counterPrice(good.getCounterPrice().doubleValue()).id(good.getId()).isHot(good.getIsHot()).isNew(good.getIsNew()).name(good.getName()).picUrl(good.getPicUrl()).retailPrice(good.getRetailPrice().doubleValue()).build();
                goodsListBeans.add(build);
            }else if (categoryId==0){
                GoodsListBean build = GoodsListBean.builder().brief(good.getBrief()).counterPrice(good.getCounterPrice().doubleValue()).id(good.getId()).isHot(good.getIsHot()).isNew(good.getIsNew()).name(good.getName()).picUrl(good.getPicUrl()).retailPrice(good.getRetailPrice().doubleValue()).build();
                goodsListBeans.add(build);
            }

            MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(good.getCategoryId());
            categories.add(marketCategory);
        }

        PageInfo<MarketGoods> pageInfo = new PageInfo<>(goods);

        selectResult.setTotal(pageInfo.getTotal());
        selectResult.setPages(pageInfo.getPages());
        selectResult.setLimit(baseParam.getLimit());
        selectResult.setPage(baseParam.getPage());
        selectResult.setFilterCategoryList(categories);
        selectResult.setList(goodsListBeans);

        return BaseRespVo.ok(selectResult);

    }

    @Override
    public BaseRespVo searchClearhistory() {
        //TODO
        //Subject subject = SecurityUtils.getSubject();
        //User user = (User) subject.getPrincipal();
        //Integer useIid = user.getId();

        // 获取当前用户ID,暂时默认user123
        Integer userId = 1;

        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        searchHistoryExample.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        int i = searchHistoryMapper.deleteByExample(searchHistoryExample);
        if (i > 0){
            return BaseRespVo.ok();
        }else {
            return BaseRespVo.fail("删除错误，请重试");
        }
    }
}
